package com.key.keypuzzlemodel

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.Nullable
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.key.keypuzzlemodel.databinding.ActivityMainBinding
import com.key.puzzlemodel.InputWebPuzzleActivity
import com.key.puzzlemodel.PuzzlePhotoActivity
import com.key.puzzlemodel.TransverseLongitudinalActivity
import com.key.puzzlemodel.config.PuzzleConfig
import com.key.puzzlemodel.config.PuzzleConfig.START_PHOTO
import com.key.puzzlemodel.cutterman.CutterManActivity
import com.key.puzzlemodel.mvvm.BaseMVVMActivity
import com.key.puzzlemodel.mvvm.BaseMVVMViewModel
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import java.io.*


class MainActivity : BaseMVVMActivity<ActivityMainBinding, BaseMVVMViewModel>(),
    View.OnClickListener {

    override val layoutId: Int
        get() = R.layout.activity_main


    //activity 回调
    var intentActivityResultLauncher: ActivityResultLauncher<Intent>? = null
    var intentActivityCutterMan: ActivityResultLauncher<Intent>? = null


    var list: ArrayList<String> = arrayListOf("a", "a1")

    override fun initView(savedInstanceState: Bundle?) {
        mVDB.clickListener = this

        //保存到 app的缓存目录下，相册无法查看
//        PuzzleConfig.init(externalCacheDir!!.path, false)
        //保存到DCIM下，相册可以查看
        PuzzleConfig.init("puzz")
        activityResult()
        if (!XXPermissions.isGranted(this@MainActivity, Permission.SYSTEM_ALERT_WINDOW)) {
            Log.e("权限", "未获取到悬浮窗权限，申请权限")
            XXPermissions.with(this)
                .permission(Permission.SYSTEM_ALERT_WINDOW)
                .request(OnPermissionCallback { permissions, allGranted ->

                    Log.e(
                        "权限",
                        "悬浮窗权限，申请权限获取 " + allGranted + "  permissions == " + permissions
                    )
                    if (!allGranted) {
                        return@OnPermissionCallback
                    }
                    Log.e("权限", "悬浮窗权限，申请权限获取成功")
                })
        }
    }


    private fun activityResult() {
        intentActivityResultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                Log.e("回调处理：", " ${it.data != null}  -- ${it.resultCode == Activity.RESULT_OK}")

                //回调处理
                if (it.resultCode == Activity.RESULT_OK) {
                    it.data?.apply {
                        val mediaPath: String? = getStringExtra(PuzzleConfig.EDIT_RESULT)
                        Log.e("返回数据：", " == $mediaPath")
                        Toast.makeText(this@MainActivity, "$mediaPath", Toast.LENGTH_SHORT).show()
                    }
                }
            }

        intentActivityCutterMan =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                Log.e(
                    "宫格回调处理：",
                    "${it.data != null}  -- ${it.resultCode}"
                )
                //宫格回调处理
                if (it.resultCode == Activity.RESULT_OK) {
                    it.data?.apply {
                        val horPicNumber: Int = getIntExtra(PuzzleConfig.HOR_PIC_NUMBER, 1)
                        val verPicNumber: Int = getIntExtra(PuzzleConfig.VER_PIC_NUMBER, 1)
                        val mediaPath: ArrayList<String>? =
                            getStringArrayListExtra(PuzzleConfig.EDIT_RESULT)
                        if (mediaPath?.isNotEmpty() == true) {
                            for (index in 0 until mediaPath!!.size) {
                                Log.e("返回数据：", " ---- index == ${mediaPath[index]}")
                            }
                        }
                        Toast.makeText(
                            this@MainActivity,
                            "horPicNumber == $horPicNumber ， verPicNumber == $verPicNumber",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
    }


    override fun onClick(view: View) {
        when (view.id) {
            R.id.card_hor_ver -> {
                KeyApplication.getInstance().optionIndex = 0
            }

            R.id.card_hor_hor -> {
                KeyApplication.getInstance().optionIndex = 1
            }

            R.id.card_cutter_man -> {
                KeyApplication.getInstance().optionIndex = 2
            }

            R.id.card_web -> {
                KeyApplication.getInstance().optionIndex = 3
            }
        }
        saveCrashInfoToFile(" \n\n\n 宫格拼图 点击事件：${KeyApplication.getInstance().optionIndex}")
        XXPermissions.with(this) // 申请单个权限
            .permission(Permission.Group.STORAGE)// 申请多个权限
            //.permission(Permission.Group.CALENDAR)
            // 申请安装包权限
            //.permission(Permission.REQUEST_INSTALL_PACKAGES)
            // 申请悬浮窗权限
            //.permission(Permission.SYSTEM_ALERT_WINDOW)
            // 申请通知栏权限
            //.permission(Permission.NOTIFICATION_SERVICE)
            // 申请系统设置权限
            //.permission(Permission.WRITE_SETTINGS)
            // 设置权限请求拦截器
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制
            //.unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    if (all) {
                        saveCrashInfoToFile("宫格拼图 onGranted：${KeyApplication.getInstance().optionIndex}")
                        onClickStartPhoto()
                    } else {
                        toast("获取部分权限成功，但部分权限未正常授予")
                    }
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {
                    if (never) {
                        toast("被永久拒绝授权，请手动授予存储权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(this@MainActivity, permissions)
                    } else {
                        toast("获取存储权限失败")
                    }
                }
            })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(this, Permission.Group.STORAGE)) {
                toast("用户已经在权限设置页授予了存储权限")
                saveCrashInfoToFile("宫格拼图 onActivityResult XXPermissions.REQUEST_CODE：${KeyApplication.getInstance().optionIndex}")
                onClickStartPhoto()
            } else {
                toast("用户没有在权限设置页授予权限")
            }
        } else if (requestCode == START_PHOTO) {
            saveCrashInfoToFile("onActivityResult 得到返回的数据 ${KeyApplication.getInstance().optionIndex}")

            if (data != null) {
                // 返回选择的图片地址list
                val arrMediaListPath = data.getStringArrayListExtra(PuzzleConfig.ALBUM_RESULT)

                if (null != arrMediaListPath && arrMediaListPath.size > 0) {
                    saveCrashInfoToFile("宫格拼图 得到数据列表大小：" + arrMediaListPath.size)
                    if (!TextUtils.isEmpty(arrMediaListPath[0])) {
                        saveCrashInfoToFile("宫格拼图 列表的第一个数据：" + arrMediaListPath[0])
                        onClickStartActivity(arrMediaListPath)
                    }
                } else {
                    Toast.makeText(this, "图片获取失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }


    fun toast(text: String) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
    }


    fun onClickStartPhoto() {
        saveCrashInfoToFile("宫格拼图 列表的第一个数据：${KeyApplication.getInstance().optionIndex}")
        when (KeyApplication.getInstance().optionIndex) {
            0 -> {
                //相册
                PuzzlePhotoActivity.startActivity(this, 2, 9, START_PHOTO)
            }

            1 -> {
                //相册
                PuzzlePhotoActivity.startActivity(this, 20, START_PHOTO)
            }

            2 -> {
                saveCrashInfoToFile("宫格拼图 onClickStartPhoto 跳转相册：${KeyApplication.getInstance().optionIndex}")
                //宫格切图
                PuzzlePhotoActivity.startActivity(this, 1, START_PHOTO)
            }

            3 -> {
                //网页拼图
                intent = Intent(this@MainActivity, InputWebPuzzleActivity::class.java)
                intentActivityResultLauncher?.launch(intent)
            }
        }
    }


    /**
     * 相册返回数据，跳转功能界面
     */
    private fun onClickStartActivity(list: ArrayList<String>) {
        var intent: Intent? = null
        saveCrashInfoToFile("跳转功能界面 onClickStartActivity：${KeyApplication.getInstance().optionIndex}")

        Log.e("相册返回", "相册地址为：" + list[0])
        when (KeyApplication.getInstance().optionIndex) {
            0 -> {
                //纵向拼图
                intent = Intent(this@MainActivity, TransverseLongitudinalActivity::class.java)
                intent.putExtra("isVertical", true)
                intent.putStringArrayListExtra(PuzzleConfig.START_PHOTO_List, list)
                intentActivityResultLauncher?.launch(intent)
            }

            1 -> {
                //横向拼图
                intent = Intent(this@MainActivity, TransverseLongitudinalActivity::class.java)
                intent.putExtra("isVertical", false)
                intent.putStringArrayListExtra(PuzzleConfig.START_PHOTO_List, list)
                intentActivityResultLauncher?.launch(intent)
            }

            2 -> {
                saveCrashInfoToFile("跳转功能界面 宫格onClickStartActivity：${KeyApplication.getInstance().optionIndex}")
                saveCrashInfoToFile("跳转功能界面 宫格onClickStartActivity：" + list.size)
                //宫格拼图
                intent = Intent(this@MainActivity, CutterManActivity::class.java)
                intent.putStringArrayListExtra(PuzzleConfig.START_PHOTO_List, list)
                intentActivityCutterMan?.launch(intent)
            }

            else -> {
                saveCrashInfoToFile("跳转功能界面 view的ID为空：${KeyApplication.getInstance().optionIndex}")
                Toast.makeText(this, "跳转失败", Toast.LENGTH_SHORT).show()
            }
        }

    }


    /**
     * 保存异常信息到本地
     *
     * @param ex
     */
    private fun saveCrashInfoToFile(printText: String) {


//        Toast.makeText(mContext, "文件保存位置：" + path + fileName, Toast.LENGTH_SHORT).show();
//        Log.e("文件保存位置：", "== $path$fileName")

        val fl = File(KeyApplication.getInstance().path)
        //创建文件夹
        if (!fl.exists()) {
            fl.mkdirs()
        }
        var fileText = printText + "\n"
        try {
            val fileOutputStream = FileOutputStream(
                KeyApplication.getInstance().path + KeyApplication.getInstance().fileName,
                true
            )
            fileOutputStream.write(fileText.toByteArray())
            fileOutputStream.close()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }


}

